import { CartItemModel } from "./declare"
import { observable, computed, action } from "mobx"
import { math } from "@/utils/math"
import { getUserId, scanCode } from '@/utils/utils';
import { network } from "@/utils/network"
import { DesktopOrderType } from '@/utils/constants';
import Taro from '@tarojs/taro'
import { sceneDesktopManager } from "./SceneDesktopManger";
import { tabbarModel } from "./Tabbar";

/**
 * 购物车model
 */
class CartModel {

  @observable
  visOrderType: boolean

  @observable
  isCatering: boolean

  @observable.ref
  items: CartItemModel[]

  @observable.ref
  shopDetail: any

  @observable.ref
  site: any

  hooks: Array<(cart: CartItemModel) => void>

  constructor() {
    this.items = []
    this.hooks = []
    this.visOrderType = false
    this.shopDetail = {}
    this.site = {}
    this.isCatering = false
  }

  @computed
  get total() {
    return this.items.reduce((p, n) => p + n.number, 0);
  }

  @computed
  get totalFree() {
    return math.format(this.items.filter(t => t.Good).reduce((p, n) => {
      return p + n.Good.price * n.number
    }, 0) / 100)
  }

  @action
  setData(cartList) {
    this.items = cartList
    this.items.forEach((it) => {
      this.hooks.length > 0 && this.hooks.forEach(hook => hook(it))
    })
  }

  @action
  setValue(key, value) {
    this[key] = value;
  }


  @action
  scanCode() {
    // 只允许从相机扫码
    this.visOrderType = false;
    scanCode();
  }

  async getData() {
    const rs = await network.get('/xxm/cart/list', {
      user_id: getUserId(),
    });
    this.setData(rs.data.list)
  }

  async getConfig() {
    const { data } = await network.get('/xxm/shop/config');
    this.shopDetail = data;
    // 不是餐饮行业，默认寄快递模式
    this.isCatering = this.shopDetail.type === 'CATERING';
    sceneDesktopManager.setShopType(this.shopDetail.type);

    // 设置tabbar
    tabbarModel.getItems(this.isCatering);
    if (!this.isCatering) {
      sceneDesktopManager.setOrderType(DesktopOrderType[1]);
    }
  }

  async getSite() {
    network.get('/api/sys/site/attr?configName=site').then(({ data, code }) => {
      if (code === 0) {
        const list = data.list || [];
        this.site = list.find(it => it.field === 'company');
      }
    });
  }


  async addCart(item: CartItemModel) {
    const { number, Good } = item;
    const user_id = getUserId();
    if (user_id) {
      const { code } = await network.post(
        '/xxm/cart/create', {
        number,
        goods_id: Good.id,
        user_id
      });

      if (code === 0) {
        this.getData();
        return true;
      }
    }
  }

  async clearCart() {
    const user_id = getUserId();
    const { code } = await network.del(
      `/xxm/cartClear/${user_id}`);
    if (code === 0) {
      this.items.forEach((it) => {
        this.hooks.length > 0 && this.hooks.forEach(hook => hook({ ...it, number: 0 }))
      })
      this.items = []
      Taro.showToast({ icon: 'success', title: '清空购物车成功' })
    }
  }

  clear() {
    this.items.forEach((it) => {
      this.hooks.length > 0 && this.hooks.forEach(hook => hook({ ...it, number: 0 }))
    })
    this.items = []
  }

}

export const cartModel = new CartModel()